package saucaca.fragment;

import java.lang.ref.WeakReference;
import java.util.List;

import lemon.kenhnhacvn.BaseActivity;
import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.MainActivity;
import lemon.kenhnhacvn.R;
import lemon.kenhnhacvn.SplashActivity;
import saucaca.Adapter.ExpandableSongAdapter;
import saucaca.Adapter.HomeVideo_HorizontalAdapter;
import saucaca.Adapter.HorizontalAdapter;
import saucaca.Adapter.ImageSlideAdapter;
import saucaca.CustomView.CustomExpandableListView;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.AlbumObject;
import saucaca.Object.HomeData;
import saucaca.Object.SlideObject;
import saucaca.Object.SongObject;
import saucaca.Slidingmenu.SlidingMenu;
import saucaca.Util.CirclePageIndicator;
import saucaca.Util.PageIndicator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class home extends Fragment {
	public static final String CMD = "0000";
	private static final long ANIM_VIEWPAGER_DELAY = 5000;
	private static final long ANIM_VIEWPAGER_DELAY_USER_VIEW = 6000;
	private Runnable animateViewPager;
	private Handler handler;

	private ViewPager mViewPager;
	TextView imgNameTxt;
	PageIndicator mIndicator;
	List<AlbumObject> albums;
	List<SongObject> videohot;
	List<SlideObject> slide;
	List<SongObject> songs;
	private SwipeRefreshLayout mSwipeLayout;
	boolean stopSliding = false;
	String message;
	private MainActivity mActivity = null;
	private CustomExpandableListView expandListview;
	private LinearLayout albumGalerry, videoGalerry;
	private ScrollView scrollViewHome;
	FragmentActivity activity;
	RequestImgTask task;
	AlertDialog alertDialog;
	TextView txtMoreAlbum, txtMoreVideo, txtMoreSong;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activity = getActivity();
	}

	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// getActivity().getActionBar().hide();
		View view = inflater.inflate(R.layout.home, container, false);
		findViewById(view);
		initHome();
		mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
		mSwipeLayout.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				sendRequest();
			}
		});
		mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);

		scrollViewHome = (ScrollView) view.findViewById(R.id.scrollview_home);
		scrollViewHome.fullScroll(ScrollView.FOCUS_UP);
		scrollViewHome.smoothScrollTo(0, 0);

		txtMoreAlbum.setOnClickListener(clickListener);
		txtMoreVideo.setOnClickListener(clickListener);
		txtMoreSong.setOnClickListener(clickListener);
		mViewPager.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				v.getParent().requestDisallowInterceptTouchEvent(true);
				switch (event.getAction()) {
				case MotionEvent.ACTION_CANCEL:
					break;

				case MotionEvent.ACTION_UP:
					if (videohot != null && videohot.size() != 0) {
						stopSliding = false;
						runnable(videohot.size());
						handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY_USER_VIEW);
					}
					break;

				case MotionEvent.ACTION_MOVE:
					if (handler != null && stopSliding == false) {
						stopSliding = true;
						handler.removeCallbacks(animateViewPager);
					}
					break;
				}
				return false;
			}
		});
		mIndicator.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageSelected(int position) {
				if (videohot != null && videohot.size() > 0) {
					SlideObject slideObject = slide.get(position);
					if (slideObject != null)
						imgNameTxt.setText(slideObject.getTXTNAME());
					switch (position) {
					case 0:
						mActivity.getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
						break;
					default:
						mActivity.getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
						break;
					}

				}
			}

		});
		mActivity.myActionBar.setMenu(R.string.menu_home, true, true);
		return view;

	}

	OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.custom_home_menu_xemthem_Album:
				((MainActivity) mActivity).switchContent(new AlbumFragmentList());
				break;
			case R.id.custom_home_menu_xemthem_Baihat:
				((MainActivity) mActivity).switchContent(new OnlineSongFragmentList());
				break;
			case R.id.custom_home_menu_xemthem_Video:
				((MainActivity) mActivity).switchContent(new VideoFragmentList());
				break;
			default:
				break;
			}
		}
	};

	public void initHome() {
		videohot = HomeData.homeListVideoHOT;
		albums = HomeData.homeListAlbum;
		songs = HomeData.homeListSong;
		slide = HomeData.homeListSlide;
		if (videohot == null) {
			sendRequest();
		} else {
			if (videohot.size() > 0) {
				mViewPager.setAdapter(new ImageSlideAdapter(activity, slide));
				new HorizontalAdapter(mActivity, albumGalerry, albums);
				new HomeVideo_HorizontalAdapter(mActivity, videoGalerry, videohot);
				expandListview.setAdapter(new ExpandableSongAdapter(activity, expandListview, songs, true));
				mIndicator.setViewPager(mViewPager);
				SlideObject song = (SlideObject) slide.get(mViewPager.getCurrentItem());
				if (song != null)
					imgNameTxt.setText(song.getTXTNAME());
				runnable(slide.size());
				handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
			} else {
				sendRequest();
			}
		}
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			mActivity = (MainActivity) activity;
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		mActivity.myActionBar.setMenu(R.string.menu_home, true, true);
	}

	private void findViewById(View view) {
		mViewPager = (ViewPager) view.findViewById(R.id.home_view_pager);
		int w = (int) (BaseActivity.w);
		int h = (int) (BaseActivity.h / 3.5);
		android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(w, h);
		mViewPager.setLayoutParams(params);
		mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
		imgNameTxt = (TextView) view.findViewById(R.id.img_name);
		albumGalerry = (LinearLayout) view.findViewById(R.id.gallery_album);
		videoGalerry = (LinearLayout) view.findViewById(R.id.gallery_Video);

		expandListview = (CustomExpandableListView) view.findViewById(R.id.expandableListView1);
		expandListview.setExpanded(true);
		expandListview.setPullLoadEnable(false);
		txtMoreAlbum = (TextView) view.findViewById(R.id.custom_home_menu_xemthem_Album);
		txtMoreVideo = (TextView) view.findViewById(R.id.custom_home_menu_xemthem_Video);
		txtMoreSong = (TextView) view.findViewById(R.id.custom_home_menu_xemthem_Baihat);
	}

	public void runnable(final int size) {
		handler = new Handler();
		animateViewPager = new Runnable() {
			public void run() {
				if (!stopSliding) {
					if (mViewPager.getCurrentItem() == size - 1) {
						mViewPager.setCurrentItem(0);
					} else {
						mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
					}
					handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
				}
			}
		};
	}

	@Override
	public void onResume() {
		if (videohot == null) {
			sendRequest();
		} else {
			mViewPager.setAdapter(new ImageSlideAdapter(activity, slide));
			mIndicator.setViewPager(mViewPager);
			imgNameTxt.setText(((SlideObject) slide.get(mViewPager.getCurrentItem())).getTXTNAME());
			runnable(videohot.size());
			handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
		}
		super.onResume();
	}

	// @Override
	// public void onDestroy() {
	// super.onDestroy();
	// if (task != null)
	// task.cancel(true);
	// try {
	//
	// } catch (Exception e) {
	// // TODO: handle exception
	// }
	// albums.clear();
	//
	// videohot.clear();
	// songs.clear();
	// albums = null;
	// videohot = null;
	// songs = null;
	// }

	@Override
	public void onPause() {
		if (task != null)
			task.cancel(true);
		if (handler != null) {
			handler.removeCallbacks(animateViewPager);
		}
		super.onPause();
	}

	private class PageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageScrollStateChanged(int state) {
			if (state == ViewPager.SCROLL_STATE_IDLE) {
				imgNameTxt.setText(((SlideObject) slide.get(mViewPager.getCurrentItem())).getTXTNAME());
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	private void sendRequest() {
		if (BaseActivity.NETWORK_CONNECTED) {
			task = new RequestImgTask(activity);
			task.execute("");
		} else {
			message = getResources().getString(R.string.error_connected);
			Toast.makeText(getActivity(), getResources().getString(R.string.error_connected), Toast.LENGTH_SHORT).show();
		}
	}

	public void showAlertDialog1(String message, final boolean finish) {
		alertDialog = new AlertDialog.Builder(activity).create();
		alertDialog.setMessage(message);
		alertDialog.setCancelable(false);

		alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				if (finish)
					activity.finish();
			}
		});
		alertDialog.show();
	}

	private class RequestImgTask extends AsyncTask<String, String, String> {
		final String TAG = "JsonReader";
		private ProgressDialog progressDialog = new ProgressDialog(getActivity());
		private final WeakReference<Activity> activityWeakRef;
		Throwable error;

		public RequestImgTask(Activity context) {
			this.activityWeakRef = new WeakReference<Activity>(context);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// progressDialog.setTitle("");
			if (!progressDialog.isShowing())
				progressDialog.show();
		}

		@Override
		protected String doInBackground(String... urls) {
			String str = null;
			str = WServiceLib.getHomeString();
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (progressDialog.isShowing())
				progressDialog.dismiss();
			if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
				if (result != null) {
					try {
						JsonReader.readHomeData(result);
						initHome();
						if (videohot != null && videohot.size() != 0) {

							mViewPager.setAdapter(new ImageSlideAdapter(activity, slide));
							new HorizontalAdapter(mActivity, albumGalerry, albums);
							new HomeVideo_HorizontalAdapter(mActivity, videoGalerry, videohot);
							expandListview.setAdapter(new ExpandableSongAdapter(activity, expandListview, songs, true));

							mIndicator.setViewPager(mViewPager);
							SlideObject song = (SlideObject) slide.get(mViewPager.getCurrentItem());
							if (song != null)
								imgNameTxt.setText(song.getTXTNAME());
							runnable(videohot.size());
							handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
						}
					} catch (Exception e) {
						Log.e(TAG, "_____Exception_______:" + e.toString());
					}
					if (HomeData.homeListMENU.size() > 0) {
						mActivity.menuFragment.SetmenuOnline();
					}
					if (mSwipeLayout.isRefreshing())
						mSwipeLayout.setRefreshing(false);
				}

			}
		}
	}
}
